import React, {Component, PropTypes} from "react";
import {Tree, Modal, message} from "antd";
import {WeaRightMenu, WeaPopoverHrm} from "ecCom";
import {stopEvent} from "../util/TreeUtil";
import {setResult} from "../actions/MyfavResultActions";
import {
    loadTree,
    expandTreeNode,
    saveAddTreeNode,
    editTreeNode,
    saveEditTreeNode,
    deleteTreeNode,
    toggleNodeOperation,
    setClickExpanded,
    updateTreeNodeData,
    handleDragNode,
    getNodeInfo,
    loadAndExpand
} from "../actions/FavouriteDirActions";

const TreeNode = Tree.TreeNode;

const confirm = Modal.confirm;

class FavDirTree extends Component {
    /**
     * 树节点加载
     * @param treeNode
     */
    loadTreeData = treeNode => {
        let {dispatch} = this.props;
        let treeKey = treeNode.props.eventKey;
        dispatch(loadTree(treeKey));
    }

    /**
     * 树节点选中
     * @param key
     * @param evt
     */
    onSelect = (key, evt) => {
        let {dispatch, selectedKey} = this.props;
        let dirId = "0";   //默认是根目录
        if (key.length > 0) {
            dirId = key[0];
        } else {    //因为选中的节点，再次点击，会取消选中，因此如果是取消选中，则使用上次选中的值
            dirId = selectedKey;
        }

        this.props.onSelect(dirId);
    }

    onExpand = (key, obj) => {
        let {dispatch} = this.props;
        let {expanded} = obj;
        let expandedKey = obj.node.props.eventKey;
        dispatch(expandTreeNode([expandedKey], expanded));
    }

    /**
     * 保存目录
     * @param evt
     */
    saveFavourite = evt => {
        let {selectedKey, dispatch} = this.props;
        for (let key in this.refs) {
            let inputObj = this.refs[key];
            let value = inputObj.value;
            if (!value) {   //值为空
                message.error("目录名称不能为空！");
                inputObj.focus();
            } else {
                let arr = key.split("_");
                if (arr.length == 3) {
                    if (key.indexOf("add") == 0) {  //新增
                        let parentid = arr[2];
                        let favname = value;
                        let favdesc = "";
                        let favorder = 0;
                        dispatch(saveAddTreeNode({parentid, favname, favdesc, favorder}));
                    } else {   //编辑
                        let favid = arr[1];
                        let parentid = arr[2];
                        let favname = value;
                        let favdesc = "";
                        let favorder = 0;
                        dispatch(saveEditTreeNode({parentid, favid, favname, favdesc, favorder}));
                    }
                }
            }
            break;
        }
    }

    /**
     * 编辑框的回车事件处理
     * @param evt
     */
    handleOnKeyDown = evt => {
        let keyCode = evt.keyCode;
        if (keyCode == 13) {  //enter key
            this.saveFavourite(evt);
        }
    }

    /**
     * 鼠标移入节点，显示操作按钮
     * @param obj
     */
    handleOnMouseEnter = (obj) => {
        let {dispatch} = this.props;
        let {eventKey} = obj.node.props;
        dispatch(toggleNodeOperation(eventKey, true));
    }

    /**
     * 鼠标移出节点，隐藏操作按钮
     * @param obj
     */
    handleOnMouseLeave = (obj) => {
        let {dispatch} = this.props;
        let {eventKey} = obj.node.props;
        dispatch(toggleNodeOperation(eventKey, false));
    }

    /**
     * 编辑节点
     * @param evt
     */
    handleOnEditNode = (evt) => {
        let {dispatch, operatingKey} = this.props;
        dispatch(editTreeNode(operatingKey));  //节点置为可编辑状态
        dispatch(setClickExpanded(false));  //不允许点击展开节点
    }

    /**
     * 删除节点
     * @param evt
     */
    handleOnDeleteNode = (evt) => {
        let {dispatch, operatingKey} = this.props;
        confirm({
            content: "该目录下的收藏条目会移动到目录\"我的收藏\"，请确认是否删除？",
            onOk() {
                dispatch(deleteTreeNode(operatingKey));
            },
            onCancel() {
            }
        });
    }

    renderComponent = (data, selectedKey) => data.map(item => {
        let {favid, favname, child, children, parentid, isinput, isover, disabled} = item;
        let isLeaf = true;

        if (!!isinput) {  //新增，或者编辑的节点，以input的形式展现
            let inputid = "edit_" + favid + "_" + parentid;  //编辑节点
            if (favid == "-9") {  //新增的节点
                inputid = "add_" + favid + "_" + parentid;
            }
            favname = (
                <input type="text" ref={inputid} style={{"width": "80px"}}
                       onBlur={this.saveFavourite} onKeyDown={this.handleOnKeyDown} defaultValue={favname}/>
            );
        } else {
            if (favid != "-1" && (!!isover || favid == selectedKey)) {   //鼠标移入或者被选中
                favname = (
                    <span>
                         <span style={{"margin-right": "30px"}}>{favname}</span>
                         <span className="icon-coms-edit" style={{"margin-right": "10px"}} title="编辑"></span>
                        {(child != "1") && (<span className="icon-coms-delete" title="删除"
                                                  onClick={this.handleOnDeleteNode}></span>)}
                    </span>
                );
            }
        }

        if (child == "1") {
            isLeaf = false;
            if (!!children) {
                return <TreeNode title={favname} key={favid}
                                 isLeaf={isLeaf}>{this.renderComponent(children, selectedKey)}</TreeNode>;
            }
        }

        return <TreeNode title={favname} key={favid} isLeaf={isLeaf}/>;
    });

    /**
     * 获取带文本框(新增或者编辑)的节点
     * @param data
     * @param addKeys
     * @param editKeys
     */
    getInputKeys = (data, addKeys, editKeys) => {
        let that = this;
        data.forEach(function (item) {
            let {favid, child, children, isinput, parentid} = item;

            if (isinput) {
                if (favid == "-9") {
                    addKeys.push(parentid);  //新增的节点，才默认展开父节点
                } else {    //记录下编辑的节点
                    editKeys.push(favid);
                }
            } else {
                if (child == "1") {
                    if (!!children) {
                        that.getInputKeys(children, addKeys, editKeys);
                    }
                }
            }
        });
    }

    onDropStart = (obj) => {
        let {dispatch} = this.props;
        let {eventKey} = obj.node.props;
        dispatch(toggleNodeOperation(eventKey, false));   //拖动后，隐藏编辑、删除按钮
    }

    onDropEnter = (obj) => {
        let {dispatch} = this.props;
        let {eventKey, expanded} = obj.node.props;
        let nodeInfo = dispatch(getNodeInfo(eventKey));   //获取节点信息
        let {child} = nodeInfo;
        if (child == "1" && !expanded) {
            dispatch(loadAndExpand(eventKey));
        }
    }

    onDrop = (obj) => {
        let {dispatch} = this.props;
        let dragKey = obj.dragNode.props.eventKey;
        let {dropPosition, dropToGap} = obj;
        let dropKey = obj.node.props.eventKey;
        let dropKeyPos = obj.node.props.pos;
        if (dragKey == "-1") {
            dispatch(setResult("0", "该目录不允许拖动！"));
        } else if (dropKey == "-1" && !dropToGap) {
            dispatch(setResult("0", "该目录不允许有下级目录！"));
        } else {
            dispatch(handleDragNode(dragKey, dropKey, dropPosition, dropToGap));
        }
    }

    componentDidUpdate() {
        for (let key in this.refs) {
            this.refs[key].focus();
            break;
        }

        let that = this;

        jQuery(".fav-left-tree .ant-tree .icon-coms-edit").on("click", function (e) {
            stopEvent();
            that.handleOnEditNode(e);
        });
    }

    render() {
        let {treeData, selectedKey, hasRadio, expandedKeys, clickExpanded} = this.props;
        const treeNodes = this.renderComponent(treeData, selectedKey);
        //新增的节点，默认展开父节点
        let addKeys = [];
        //编辑的节点
        let editKeys = [];
        this.getInputKeys(treeData, addKeys, editKeys);

        return (
            <Tree onSelect={this.onSelect}
                  loadData={this.loadTreeData}
                  onExpand={this.onExpand}
                  onMouseEnter={this.handleOnMouseEnter}
                  onMouseLeave={this.handleOnMouseLeave}
                  showLine={true}
                  defaultSelectedKeys={["-1"]}
                  selectedKeys={[selectedKey]}
                  expandedKeys={expandedKeys}
                  hasRadio={hasRadio}
                  clickNodeExpandChildren={clickExpanded}
                  draggable={true}
                  onDragEnter={this.onDropEnter}
                  onDrop={this.onDrop}
                  onDragStart={this.onDropStart}>
                {treeNodes}
            </Tree>
        );
    }
}

FavDirTree.PropTypes = {
    onSelect: React.PropTypes.func.isRequired,
    hasRadio: React.PropTypes.bool
}

export default FavDirTree;
